package com.example.myapplication.ui.activity.coins

import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.chad.library.adapter.base.loadmore.SimpleLoadMoreView
import com.example.myapplication.R
import com.example.myapplication.arouter.ARouterPath
import com.example.myapplication.ui.adapter.RankAdapter
import com.kun.base.ui.AbsBaseActivity
import com.scwang.smart.refresh.header.ClassicsHeader
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.android.synthetic.main.toolbar_layout.*

/**
 *积分排行的activity
 *
 * @author : Kun
 * @date : 2021/6/11
 * @time : 10:29
 */
@Route(path = ARouterPath.RANK)
class RankActivity : AbsBaseActivity() {

    private var index = 1

    private lateinit var rankAdapter: RankAdapter
    private lateinit var rankViewModel: RankViewModel

    override fun getLayoutId(): Int {
        return R.layout.activity_rank
    }

    override fun initViewModel() {
        rankViewModel = getActivityScopeViewModel(RankViewModel::class.java)
        rankViewModel.coinsRequest.rankListResult.observe(this, Observer { t ->
            if (t.errorCode == 0) {
                if (t.data!!.curPage == 1) {
                    rankAdapter.setList(t.data!!.datas)
                } else {
                    rankAdapter.addData(t.data!!.datas)
                }
                if (t.data!!.curPage >= t.data!!.pageCount) {
                    rankAdapter.loadMoreModule.loadMoreEnd()
                } else {
                    rankAdapter.loadMoreModule.loadMoreComplete()
                }
            } else {
                rankAdapter.loadMoreModule.loadMoreComplete()
            }
            refresh_layout!!.finishRefresh()

        })
    }

    override fun initView() {
        iv_back.setOnClickListener { finish() }
        tv_title.text = getString(R.string.coins_rank)

        refresh_layout!!.setRefreshHeader(ClassicsHeader(this))
        rankAdapter = RankAdapter(R.layout.item_rank, null)
        rankAdapter.loadMoreModule.loadMoreView = SimpleLoadMoreView()


        recycler_view!!.layoutManager = LinearLayoutManager(this)
        recycler_view!!.adapter = rankAdapter

        rankAdapter.loadMoreModule.setOnLoadMoreListener {
            //加载更多
            index++
            getData()
        }
        refresh_layout!!.setOnRefreshListener {
            //刷新数据
            index = 1
            getData()
        }

        getData()
    }

    private fun getData() {
        rankViewModel.requestRankListResult(index)
    }
}